<?php
namespace App\Console\Commands\Listing;
use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

/**
 * Class MultithreadingRequest
 * @package App\Console\Commands\Listing
 * @desc 多线程请求
 */
class MultithreadingRequest extends Command
{
    private $concurrency    = 7;  // 同时并发抓取
    private $log            = '';
    protected $signature = 'test:pool';
    protected $description = '测试多线程请求';

    public function __construct()
    {
        parent::__construct();
        $this->log = new Logger('testPool');
        $streamHander1 = new StreamHandler(storage_path('logs/testPool.log'), Logger::INFO);
        $this->log->pushHandler($streamHander1);
    }

    public function handle()
    {

        try {

            $deptList = ['CycloneAxe', 'appleboy', 'Aufree', 'lifesign',
                'overtrue', 'zhengjinghua', 'NauxLiu'];
            //dd($deptList);
            $client = new Client();
            $requests = function ($deptList) {
//                $url = "www.ntebay.com/listing/listing/oa/deptuser?";
                foreach ($deptList as $dept) {
                    $url = route('oa.pool', ['user' => $dept]);
                    dump($url);
                    yield new Request('Get', $url);
                }
            };

            $pool = new Pool($client, $requests($deptList), [
                'concurrency' => $this->concurrency,
                'fulfilled' => function ($response, $index) {
                    Log::channel('testPool')->info($response->getBody()->getContents());
                },
                'rejected' => function ($reason, $index) {
                    $this->log->info('错误请求: '.$reason);
                },
            ]);
            $promise = $pool->promise();
            $promise->wait();
    }catch(\Exception $e){
           $this->log->info($e->getMessage());
        }
        dd('SUCCESS');
    }


}
